<template>
	<el-dialog v-model="currentVisible" :class="$style['dialog-dahua-player']"
		:title="title || (currentType == 'real' ? '视频详情' : '录像详情')" :close-on-click-modal="false"
		:close-on-press-escape="false" @closed="handleResetDialog" v-if="useDahuaVideo">
		<template v-if="!!currentChannels.length">
			<!-- <DahuaPlayer ref="refDahuaPlayer" :el="el" :pztEl="pztEl" :type="currentType" :channels="currentChannels"
				:defaultWindowNumber="1" :maxWindow="1" :startTime="currentStartTime" :endTime="currentEndTime"
				v-if="currentType == 'real'" /> -->
			<div id="dialog-dahua-player-plugin" style="height: 100%;"></div>
		</template>
	</el-dialog>
	<div v-else v-show="false"></div>
</template>

<script>
import { ref, watch, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import http from '@/utils/http'
import DahuaPlayer from '@/components/DahuaPlayer.vue'
import useEventBus from '@/utils/event.bus'
import CyPlayerCls from '@/utils/cy.player'
import DahuaPlayerPlugin from '@/utils/dahua.player.plugin'
import VueTypes from 'vue-types'

export default {
	name: 'dialog-dahua-video',
	components: {
		DahuaPlayer
	},
	props: {
		// [real: 实时预览, record: 录像回放]
		value: VueTypes.bool.def(false),
		type: VueTypes.oneOf(['real', 'record']).def('real'),
		title: VueTypes.string.def(''),
		el: VueTypes.string.def('dialog-event-video'),
		pztEl: VueTypes.string.def(''),
		operation: VueTypes.shape({
			streamChangeSelect: Boolean, // 主辅码流切换
			localRecordIcon: Boolean, // 本地录像功能按钮
			audioIcon: Boolean, // 开启关闭声音按钮
			snapshotIcon: Boolean, // 抓图按钮
			closeIcon: Boolean, // 关闭视频按钮
			extendIcons: VueTypes.any
		}).def({
			streamChangeSelect: true,
			localRecordIcon: true,
			audioIcon: true,
			snapshotIcon: true,
			closeIcon: true,
			extendIcons: null
		}).loose,
		channels: VueTypes.array.def([]),
		// 录像开始时间，单位为秒或者是完整的日期 [YYYY-MM-DD HH:mm:ss]
		startTime: VueTypes.oneOfType([String, Number]).def(''),
		// 录像结束时间，单位为秒或者是完整的日期 [YYYY-MM-DD HH:mm:ss]
		endTime: VueTypes.oneOfType([String, Number]).def(''),
		// 存储位置类型包括 [2:中心录像, 3:设备录像], 默认为 2
		recordSource: VueTypes.oneOfType([String, Number]).def(2)
	},
	emits: ['update:value'],
	setup(props, { emit }) {
		const useDahuaVideo = window.dahuaVideo
		const refDahuaPlayer = ref(null)
		const currentVisible = ref(props.value)
		const currentType = ref(props.type)
		const currentChannels = ref(props.channels)
		const currentStartTime = ref(props.startTime)
		const currentEndTime = ref(props.endTime)
		const eventBus = useEventBus()

		let cyPlayer = new CyPlayerCls()
		let dahuaPlayerCls = new DahuaPlayerPlugin({
			el: 'dialog-dahua-player-plugin',
			exclusion: false
		})

		let recordDuration = 1000 * 60 * 10

		const getConfiguration = () => {
			http.get('v1/special/info', { params: { id: 3 } }).then(res => {
				if (res.code === 1) {
					const eventRecordConfig = res.data || { duration: 600 }
					recordDuration = eventRecordConfig.duration * 1000
				}
			})
		}

		/**
		 * 显示视频
		 * @param {String} type [real, record] 
		 * @param {channel[]} channels 视频通道
		 * @param {Date} startTime 录像的开始时间
		 * @param {Date} endTime 录像的结束时间
		 * @param {Boolean} useRecordDuration 录像时候追加前后时长
		 */
		const open = ({ type, channels = [], title, startTime, endTime, useRecordDuration }, cyData = {}) => {
			// console.log('🚀 ~ open ~ type:', type)
			currentType.value = type
			const cyVideoList = cyData || []
			const cyRecordList = cyData || []

			if (!channels.length || (!cyVideoList.length && !cyRecordList.length)) {
				ElMessage({
					type: 'error',
					message: `没有可播放的${props.type === 'real' ? '视频' : '录像'}`
				})

				return
			}
			eventBus.emit('dahua:open')
			if (!useDahuaVideo) {
				switch (type) {
					case 'real':
						cyPlayer.playRealVideo({
							title: title,
							list: cyVideoList
						})

						break
					case 'record':
						cyPlayer.playRecordVideo({
							title: title,
							type: 1,
							event_time: cyData.event_time,
							list: cyRecordList
						})

						break
					default:
						break
				}
				return
			}

			currentVisible.value = true
			currentType.value = type ?? props.type
			currentStartTime.value = startTime ?? props.startTime
			currentEndTime.value = endTime ?? props.endTime
			currentChannels.value = channels ?? []
			// console.log('🚀 ~ open ~ currentEndTime.value:', useRecordDuration, recordDuration, currentStartTime.value, currentEndTime.value)

			// if (type === 'real') {
			// 	return
			// }

			nextTick(() => {
				dahuaPlayerCls.login(() => {
					dahuaPlayerCls.initLayout(type === 'real' ? 1 : 2, currentChannels.value.map((chl, index) => {
						return {
							...chl,
							beginTime: currentStartTime.value - (useRecordDuration ? recordDuration : 0),
							endTime: currentEndTime.value + (useRecordDuration ? recordDuration : 0),
							index
						}
					}))
				})
			})
		}

		const handleResetDialog = () => {
			dahuaPlayerCls?.destroy(true)
			currentChannels.value = []
			currentVisible.value = false

			eventBus.emit('dahua:close')

			emit('update:value', false)
		}

		// 监听报警弹窗打开关闭事件
		const AlarmDialogOpenlistener = () => {
			if (currentVisible.value) {
				dahuaPlayerCls?.hidden()
			}
		}

		// 监听报警弹窗关闭事件
		const AlarmDialogCloselistener = () => {
			if (currentVisible.value) {
				dahuaPlayerCls?.visible()
			}
		}

		// 绑定监听报警弹窗打开关闭事件
		eventBus.on('dahua:alarm:open', AlarmDialogOpenlistener)
		eventBus.on('dahua:alarm:close', AlarmDialogCloselistener)

		watch(
			() => props.value,
			visible => {
				if (!useDahuaVideo) {
					return
				}

				if (visible && !props.channels.length) {
					ElMessage({
						type: 'error',
						message: `没有可播放的${props.type === 'real' ? '视频' : '录像'}`
					})

					currentVisible.value = false
					emit('update:value', false)

					return
				}

				currentVisible.value = visible
				visible ? eventBus.emit('dahua:open') : eventBus.emit('dahua:close')
			}
		)

		watch(
			() => props.type,
			(type) => {
				currentType.value = type
			}
		)

		watch(
			() => props.channels,
			(channels) => {
				currentChannels.value = channels
			}
		)

		watch(
			() => props.startTime,
			(time) => {
				currentStartTime.value = time
			}
		)

		watch(
			() => props.endTime,
			(time) => {
				currentEndTime.value = time
			}
		)

		onBeforeUnmount(() => {
			currentChannels.value = []
			currentVisible.value = false
			eventBus.off('dahua:alarm:open', AlarmDialogOpenlistener)
			eventBus.off('dahua:alarm:close', AlarmDialogCloselistener)

			cyPlayer = null
			dahuaPlayerCls.destroy()
			dahuaPlayerCls = null
		})
		if (window.dahuaVideo) {
			getConfiguration()
		}

		return {
			useDahuaVideo,
			refDahuaPlayer,
			currentType,
			currentVisible,
			currentChannels,
			currentStartTime,
			currentEndTime,
			handleResetDialog,
			open
		}
	}
}
</script>

<style lang="scss" module>
.dialog-dahua-player {
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	height: calc(100vh - 20vh);
	margin: 10vh auto;

	& [class~="el-dialog__body"] {
		flex: 1 0 0;
		width: 100%;
		height: 0;
		padding: 0;
	}
}
</style>
